package esayexcel.demo;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.WriteSheet;
import esayexcel.bean.User;
import org.apache.poi.ss.usermodel.*;

import java.io.FileOutputStream;
import java.util.*;


public class ExcelExportExample {
    public static void main(String[] args) throws Exception{
        // 准备数据
        List<List<String>> dataList = new ArrayList<>();
        dataList.add(Arrays.asList("序号", "测试内容", "单位", "改造前", "改造后"));
        dataList.add(Arrays.asList("序号", "测试内容", "单位", "改造前", "改造后"));
        dataList.add(Arrays.asList("1", "测试A", "/", "100", "200"));
        dataList.add(Arrays.asList("2", "测试B", "小时",  "1000", "2000"));
        List<List<String>> headList = new ArrayList<>();
        headList.add(Arrays.asList("空调节能项目测试报告"));

        // 写入Excel文件`
        String fileName = "D:\\users.xlsx";
        FileOutputStream outputStream = new FileOutputStream(fileName);
        ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
        Map<Integer, Integer> colWidthMap = new HashMap<>();
        colWidthMap.put(3, 50);
        colWidthMap.put(4, 50);
        Map<Integer, Integer> rowHeightMap = new HashMap<>();
        rowHeightMap.put(10, 90);
        String reportSheetName = "测试报告";
        int[] mergeColumnIndex = {0, 1, 2};
        WriteSheet sheet = EasyExcel.writerSheet(1, reportSheetName).head(headList)
                //合并单元格的艺术在这里
        .registerWriteHandler(new DynamicHeaderHandler())
                .registerWriteHandler(new DynamicHeaderHandler(1, 2, mergeColumnIndex))
                .registerWriteHandler(new DynamicHeaderHandler(1, 2, 3,4))
                .registerWriteHandler(new DynamicHeaderHandler(2, 2, 3,4))
                .registerWriteHandler(new CellWriteHandler() {
                    @Override
                    public void afterCellDispose(CellWriteHandlerContext context) {
                        context.getFirstCellData().setWriteCellStyle(null);
                        //Excel自定义样式
                        Cell cell = context.getCell();
                        Workbook workbook = cell.getSheet().getWorkbook();
                        CellStyle cellStyle = workbook.createCellStyle();
                        cellStyle.setWrapText(true);
                        cellStyle.setAlignment(HorizontalAlignment.CENTER);
                        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                        cell.setCellStyle(cellStyle);
                    }
                })
                .build();
        excelWriter.write(dataList, sheet);
        excelWriter.finish();
    }
}
